/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

const csv = require('csvtojson');
const fs = require('fs');

/**
 * csv转换成需要的JSON数据
 *  */

csv()
  .fromFile('./dist/village.csv')
  .then((jsonObj = []) => {
    let jsonData = {};
    let arr = [];

    jsonObj.forEach((val = {}) => {
      const [countyCode, countyName, townCode, townName, villageCode, villageName] = Object.values(
        val,
      );
      arr.push({
        countyCode,
        countyName,
        townName,
        townCode,
      });
    });

    // 去重
    let map = new Map();
    for (const item of arr) {
      if (!map.has(item.townCode)) {
        map.set(item.townCode, item);
      }
    }

    arr = [...map.values()];

    console.log('arr', arr);

    jsonData = arr.reduce((acc, obj) => {
      let key = obj.countyCode.substring(0, 6);

      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push({
        [obj.townName]: obj.townCode,
      });
      return acc;
    }, {});

    fs.writeFile('./source/csvJson.json', JSON.stringify(jsonData), { encoding: 'utf-8' }, _err => {
      if (_err) {
        console.log('file_err', _err);
      }
    });
  });
